<template>
  <!-- 学生社团详情 -->
  <div class="app-container">
      <el-form
        :model="queryParams"
        ref="queryForm"
        size="small"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
      <el-form-item label="学期" prop="schoolYear">
        <el-select
          v-model="queryParams.schoolYear"
          placeholder="请选择"
          style="width: 240px"
        >
          <el-option
            v-for="option in schoolYearList"
            :key="option.schoolYearId"
            :label="option.schoolYearId"
            :value="option.schoolYearId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="期" prop="period">
        <el-select
          v-model="queryParams.period"
          placeholder="请选择"
        >
          <el-option
            v-for="option in timeList"
            :key="option.dictCode"
            :label="option.dictValue"
            :value="option.dictValue"
          />
        </el-select>
      </el-form-item>
        <el-form-item label="学生">
          <el-input placeholder="请输入" clearable v-model="queryParams.stuIdOrStuName" class="input-with-select">
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="mini" @click="getList(orgForm, '-1')">搜索</el-button>
          <el-button type="primary" icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
        </el-form-item>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              v-hasPermi="['organ:studentOrgan:add']"
              @click="handleAdd"
              >添加学生</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              v-hasPermi="['organ:studentOrgan:export']"
              @click="handleImport"
              >批量导入学生</el-button
            >
            <el-button
              type="primary"
              size="mini"
              @click="exportC"
              v-hasPermi="['organ:studentOrgan:export']"
              >选择导入学生</el-button>
            <el-button
              size="mini"
              type="danger"
              :disabled='multiple'
              v-hasPermi="['organ:studentOrgan:del']"
              @click="handleDelete"
              >删除</el-button
            >
          </el-col>
        </el-row>
      </el-form>
      <el-table
        border
        v-loading="loading"
        :data="memberList"
        @selection-change="handleSelectionChange"
      >
      <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="学号" align="center" prop="studentId" />
        <el-table-column label="学生" align="center" prop="studentName" />
        <el-table-column label="性别" align="center" prop="sex" />
        <el-table-column label="期数" align="center" prop="period" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="200"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope" v-if="isCanRead || name == scope.row.studentId">
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)"
              v-hasPermi="['organ:studentOrgan:del']"
              style="padding-left: 10px; padding-right: 10px"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />



      <!-- 添加学生 -->
      <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="学号" prop="studentId">
            <el-select
            v-model="form.studentId"
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词"
            :remote-method="remoteMethod"
            :loading="searchLoading"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          </el-form-item>
          <!-- <el-form-item label="姓名" prop="studentName">
            <el-input
              v-model="form.studentName"
              placeholder="请输入姓名"
              style="width: 240px"
            ></el-input>
          </el-form-item> -->
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>

      <!-- 用户导入对话框 -->
      <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
        <el-upload
          ref="upload"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="
            upload.url
          "
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip text-center" slot="tip">
            <div class="el-upload__tip" slot="tip">
              <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate"
              >下载模板</el-link
            >
          </div>
        </el-upload>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </el-dialog>
      <el-dialog title="选择性导入学生" :visible.sync="open1" width="800px" append-to-body>
        <el-form ref="formRef" :model="formModel1" inline size="mini">
          <el-form-item label="系部/班级" prop="studentId">
            <el-select v-model="formModel1.type" placeholder="请选择" @change="change($event)">
              <el-option v-for="dict in dictValue" :key="dict.dictValue" :label="dict.dictLabel"
                :value="dict.dictValue"></el-option>
            </el-select>
            <el-select v-model="formModel1.name" placeholder="请选择" style="margin-left: 20px;">
              <el-option v-for="(dict,idx) in classList" :key="idx" :label="dict"
                :value="dict"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="mini" @click="loadData1" :disabled='!formModel1.name'>查询</el-button>
            <el-button type="primary" @click="submitFileForm1" :disabled='multiple'>批量导入</el-button>
          </el-form-item>
        </el-form>
        <el-table border :data="studentList" @selection-change="handleSelectionChange1">
          <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="学号" align="center" prop="userName" />
            <el-table-column label="姓名" align="center" prop="nickName" />
        </el-table>
        <pagination
        v-show="total1 > 1"
        :total="total1"
        :page.sync="pageNum1"
        :limit.sync="pageSize1"
        @pagination="loadData1"
      />
      <!-- <el-pagination
      v-show="total1>0"
      background
      layout="prev, pager, next"
      :total="total1">
      </el-pagination> -->
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
        </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import { getToken } from '@/utils/auth';
import { GetYearList } from '@/api/organ/organ';
import Clipboard from 'clipboard';
import {
  listMember,
  getMember,
  delMember,
  addMember,
  updateMember,
  summary,
} from '@/api/organ/studentOrganMember';
import { GetActivityMemberList, GetActivityMemberList1, ActivityReplaceSign, GetDict, getClassList} from '@/api/activity';
import {
  listOrg,
  getOrg,
  delOrg,
  addOrg,
  updateOrg,
  getstudentmanager,
  setstudentmanager,
  unitNameList,
  editState,
  addList
} from '@/api/organ/studentOrgan';
import {
  getTime
} from '@/api/organ/studentOrgan';
export default {
  name: 'Member',
  dicts: ['sys_show_hide', 'orgMemberStatus', 'markStatus', 'orgStatus'],
  computed: {
    ...mapGetters(['roles', 'name', 'userName','unitName']),
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      names: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 成员任命信息表格数据
      memberList: [],
      // 成员历史任职
      historyList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      open1: false,
      timeList:[],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        period: null,
        schoolYear: null,
      },
      // 表单参数
      form: {},
      formModel1: {},
      // 表单校验
      rules: {
        orgId: [{ required: true, message: '组织ID不能为空', trigger: 'blur' }],
      },
      orgForm: {},
      activeName: 'first',
      schoolYearList: [],
      positionIdList: [
        {
          name: '技术部成员',
          code: '1',
        },
      ],
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: '',
      },
      // 是否选了任职人员
      isStudentId: false,
      historyOpen: false,
      markOpen: false,
      updateStateOpen: false,
      searchLoading: false,
      options: [],
      markFrom: {},
      classList:[],
      studentList:[],
      writeMark: false,
      // 是否可以审核
      canWrite: false,
      isCanRead: false,
      dictValue:[],
      selectionList:[],
      total1:0,
      pageNum1:1,
      pageSize1:10
    };
  },
  created() {
    GetYearList().then(response => { 
      this.schoolYearList = response.rows;
      for (let i  = 0; i  < response.total; i ++) {
        if(response.rows[i].defaultValue == "1"){
          console.log(response.rows[i],"year")
          this.queryParams.schoolYear = response.rows[i].schoolYearId;
        }
      }
      getTime(this.queryParams.schoolYear).then(res=>{
        this.queryParams.period = res.data[0].dictLabel
        this.timeList = res.data
        this.getList()
        this.canRead()
      })
    });
    const pid = this.$route.params && this.$route.params.pid;
    getOrg(pid).then(response => {
      this.orgForm = response.data;
      this.canWrite = this.orgForm.orgStatus === '0' ? true : false;
      console.log(this.orgForm);
    });
    
  },
  methods: {
    exportC(){
      this.total1=0;
      this.pageNum1=1;
      this.pageSize1=10;
      this.reset();
      this.getValue()
      this.open1 = true
    },
    getValue(){
      GetDict().then(res=>{
        this.dictValue = res.data
      })
    },
    handleSelectionChange1(selection){
      this.selectionList = selection
      console.log(this.selectionList);
      this.multiple = !selection.length;
    },
    change(e){
      getClassList(e).then(res=>{
        this.classList = res.data
        console.log(res);
      })
    },
    loadData1(){
      this.reset();
      this.loading = true;
      const payload = {
        pageNum: this.pageNum1,
        pageSize: this.pageSize1,
        ...this.formModel1,
      };
      GetActivityMemberList1(payload).then(res=>{
        this.loading = false;
        const { rows, total: rowTotal } = res;
        this.studentList = rows
        this.total1 = rowTotal
      })
    },
    submitFileForm1(){
      const pid = this.$route.params && this.$route.params.pid;
      const payload = {
        activityMemberList:this.selectionList,
        orgId:pid,
        schoolYear:this.queryParams.schoolYear,
        period:this.queryParams.period,
      }
      console.log(payload);
      addList(payload).then(res=>{
        this.getList()
        this.cancel()
      })
    },
    copy(type){
      var clipboard = new Clipboard('.tag-read');
      clipboard.on('success', e => {
        console.log('复制成功');
        this.$modal.msgSuccess((type==1?'职位审核链接':'考核审核链接') + '复制成功');
        // 释放内存
        clipboard.destroy();
      });
      clipboard.on('error', e => {
        // 不支持复制
        console.log('该浏览器不支持自动复制');
        this.$modal.msgError("该浏览器不支持自动复制");
        // 释放内存
        clipboard.destroy();
      });
    },
    // 判断是否能读取后三列
    canRead() {
      var isCanRead = false;
      if (this.roles) {
        console.log(this.roles, 'roles');
        for (let i = 0; i < this.roles.length; i++) {
          if (['admin', 'common'].includes(this.roles[i])) {
            isCanRead = true;
            break;
          } else if (['teacher3'].includes(this.roles[i])) {
            if (this.unitName == this.orgForm.unitName) {
              isCanRead = true;
              break;
            }
          } else if (this.name == this.orgForm.teacherId || this.name == this.orgForm.studentId) {
            isCanRead = true;
            break;
          }
        }
      }
      console.log(isCanRead, 'isCanRead');
      this.isCanRead = isCanRead;
      return isCanRead;
    },
    getList(item, isHavaPosition) {
      this.loading = true;
      const pid = this.$route.params && this.$route.params.pid;
      let data = {
        orgId:pid,
        ...this.queryParams
      }
      listMember(data).then(response => {
        this.memberList = response.rows;
        //console.log(this.memberList)
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.open1 = false;
      this.formModel1.type = ''
      this.formModel1.name = ''
      this.reset();
    },
    // 取消按钮
    markCancel() {
      this.updateStateOpen = false;
      this.orgForm.orgStatus = '0';
    },

    // 表单重置
    reset() {
      this.studentList = []
      this.form = {
        studentId: null,
        studentName: null,
      };
      this.resetForm('form');
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      // this.resetForm('queryForm');
      this.queryParams.stuIdOrStuName = ''
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.names = selection.map(item => item.studentName);
      this.ids = selection.map(item => item.orgMemberId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.options = []
      this.reset();
      this.open = true;
    },
    // 批量任命信息导入按钮
    handleImport() {
      this.upload.title = '批量导入学生';
      this.upload.open = true;
      this.upload.url = process.env.VUE_APP_BASE_API + '/committee/member/importStudentData?' + 'orgId=' + this.orgForm.orgId + '&schoolYear=' + this.queryParams.schoolYear + '&period=' + this.queryParams.period
      console.log(this.upload.url);
    },
    /** 下载模板操作 */
    importTemplate() {
      if(this.upload.title == '批量导入学生'){
        this.download(
        '/committee/member/importStudentDataTemplate',
        {},
        `studentUnionOrgan_template_${new Date().getTime()}.xlsx`
      )
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'committee/member/export',
        {
          ...this.queryParams,
        },
        `member_${new Date().getTime()}.xlsx`
      );
    },
    // 批量考核导入按钮
    handleImportStu(){
      this.upload.title = '批量考核信息导入';
      this.upload.open = true
      this.upload.url = process.env.VUE_APP_BASE_API + '/committee/member/import' + '?updateSupport=' + this.upload.updateSupport + '&orgId=' + this.orgForm.orgId
      console.log(this.upload.url);
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          '</div>',
        '导入结果',
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 查看历史任职
    seeHistory(row) {
      this.title = '查看 ' + row.studentName + ' 历史任命';
      this.historyList = row.positionNameList;
      console.log(this.historyList, 'history');
      this.historyOpen = true;
    },
    /**查看考核按钮操作 */
    markDetail(row) {
      this.writeMark = false;
      this.markOpen = true;
      this.markFrom = row;
      console.log(this.markFrom);
    },
    /**查看填写工作日志操作 */
    writeMarkHandle(row) {
      this.writeMark = true;
      this.markOpen = true;
      this.markFrom = row;
      console.log(this.markFrom);
    },
    summary() {
      summary(this.markFrom).then(response => {
        this.markOpen = false;
        this.getList();
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const orgMemberId = row.orgMemberId || this.ids;
      getMember(orgMemberId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = '修改成员任命信息';
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.form.orgId = this.orgForm.orgId;
          console.log(this.form);
          let data = {
            schoolYear:this.queryParams.schoolYear,
            period:this.queryParams.period,
            ...this.form
          }
          console.log(data);
          addMember(data).then(response => {
            console.log(response);
            if(response.code == 200){
              this.$modal.msgSuccess('操作成功');
              this.open = false;
              this.getList();
            }
          });
        }
      });
    },
    /** 社团审核按钮 */
    updateState() {
      console.log(this.orgForm.orgStatus === '1', 'orgStatus');
      this.updateStateOpen = true;
    },
    // 社团审核提交按钮
    submitFormUpdate() {
      this.$refs['orgForm'].validate(valid => {
        if (valid) {
          if (this.orgForm.orgStatus !== '0') {
            console.log(this.orgForm, 'orgForm');
            editState(this.orgForm).then(response => {
              if (response.code == 200) {
                this.$modal.msgSuccess('审核成功');
                this.updateOpen = false;
                this.getList();
              }
            });
            this.updateStateOpen = false;
            this.canWrite = false;
          } else {
            this.$modal.msgError('请选择审核结果！');
          }
        }
      });
    },
    /** 删除社团操作 */
    handleDeleteOrg(row) {
      const orgIds = row.orgId || this.ids;
      this.$modal
        .confirm('是否确认删除组织信息编号为"' + orgIds + '"的数据项？')
        .then(function () {
          return delOrg(orgIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess('删除成功');
          this.$router.go(-1);
        })
        .catch(() => {});
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const name = row.studentName || this.names
      const orgMemberIds = row.orgMemberId || this.ids;
      this.$modal
        .confirm('是否确认删除学生姓名为"' + name + '"的数据？')
        .then(function () {
          return delMember(orgMemberIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess('删除成功');
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'committee/member/export',
        {
          ...this.queryParams,
        },
        `member_${new Date().getTime()}.xlsx`
      );
    },
    /** 切换标签卡 */
    handleClick(tab, event) {
      if (tab.index == '0') {
        this.showSearch = true;
      } else {
        this.showSearch = false;
      }
    },
    /** 查询学生管理员 */
    remoteMethod(query) {
      if (query !== '') {
        this.loading = true;
        getstudentmanager(query).then(response => {
          this.loading = false;
          this.options = response.rows.filter(item => {
            return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
          });
        });
      } else {
        this.options = [];
      }
    },
  },
};
</script>
